﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Project.Core.Config.Config.Jwt {
    public class JwtToken {

        public static string GetToken(JwtConfigInfo jwtConfig, string username, List<string> roles) {
            
            //定义许多种的声明Claim,信息存储部分,Claims的实体一般包含用户和一些元数据
            IEnumerable<Claim> claims = new Claim[]{
                new Claim(ClaimTypes.Name, username)
            };

            //添加用户权限
            foreach (var role in roles) {
                claims = claims.Append(new Claim(ClaimTypes.Role, role));
            }

            //notBefore  生效时间
            var nbf = DateTime.UtcNow;
            //expires   //过期时间
            var exp = DateTime.UtcNow.AddSeconds(Convert.ToDouble(jwtConfig.Expires));
            //signingCredentials  签名凭证
            string sign = jwtConfig.SigningKey;
            var secret = Encoding.UTF8.GetBytes(sign);
            var key = new SymmetricSecurityKey(secret);
            var signcreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(claims: claims, notBefore: nbf, expires: exp, signingCredentials: signcreds);
            var JwtHander = new JwtSecurityTokenHandler();
            var token = JwtHander.WriteToken(jwt);
            return token;
        }
    }
}
